import { MigrationInterface, QueryRunner, Table, TableForeignKey } from 'typeorm';

export class AddCreditTables1703000000003 implements MigrationInterface {
  public async up(queryRunner: QueryRunner): Promise<void> {
    // 创建用户积分表
    await queryRunner.createTable(
      new Table({
        name: 'user_credits',
        columns: [
          {
            name: 'id',
            type: 'int',
            isPrimary: true,
            isGenerated: true,
            generationStrategy: 'increment',
          },
          {
            name: 'user_id',
            type: 'int',
            isUnique: true, // 每个用户只有一条积分记录
          },
          {
            name: 'credit_balance',
            type: 'int',
            default: 0,
          },
          {
            name: 'expires_at',
            type: 'timestamp',
            isNullable: true,
          },
          {
            name: 'created_at',
            type: 'timestamp',
            default: 'CURRENT_TIMESTAMP',
          },
          {
            name: 'updated_at',
            type: 'timestamp',
            default: 'CURRENT_TIMESTAMP',
            onUpdate: 'CURRENT_TIMESTAMP',
          },
        ],
      }),
      true
    );

    // 创建积分交易记录表
    await queryRunner.createTable(
      new Table({
        name: 'credit_transactions',
        columns: [
          {
            name: 'id',
            type: 'varchar',
            length: '36',
            isPrimary: true,
            generationStrategy: 'uuid',
            default: '(UUID())',
          },
          {
            name: 'user_id',
            type: 'int',
          },
          {
            name: 'transaction_type',
            type: 'enum',
            enum: ['purchase', 'usage', 'refund', 'expiration'],
          },
          {
            name: 'credit_amount',
            type: 'int',
          },
          {
            name: 'description',
            type: 'text',
            isNullable: true,
          },
          {
            name: 'reference_id',
            type: 'varchar',
            length: '255',
            isNullable: true,
          },
          {
            name: 'metadata',
            type: 'json',
            isNullable: true,
          },
          {
            name: 'created_at',
            type: 'timestamp',
            default: 'CURRENT_TIMESTAMP',
          },
        ],
      }),
      true
    );

    // 创建外键约束
    await queryRunner.createForeignKey(
      'user_credits',
      new TableForeignKey({
        columnNames: ['user_id'],
        referencedColumnNames: ['id'],
        referencedTableName: 'users',
        onDelete: 'CASCADE',
      })
    );

    await queryRunner.createForeignKey(
      'credit_transactions',
      new TableForeignKey({
        columnNames: ['user_id'],
        referencedColumnNames: ['id'],
        referencedTableName: 'users',
        onDelete: 'CASCADE',
      })
    );

    // 创建索引
    await queryRunner.query(`
      CREATE INDEX idx_credit_transactions_user_id ON credit_transactions(user_id);
    `);
    
    await queryRunner.query(`
      CREATE INDEX idx_credit_transactions_created_at ON credit_transactions(created_at);
    `);

    await queryRunner.query(`
      CREATE INDEX idx_user_credits_expires_at ON user_credits(expires_at);
    `);
  }

  public async down(queryRunner: QueryRunner): Promise<void> {
    // 删除外键约束
    const userCreditsTable = await queryRunner.getTable('user_credits');
    const creditTransactionsTable = await queryRunner.getTable('credit_transactions');

    if (userCreditsTable) {
      const userCreditsForeignKey = userCreditsTable.foreignKeys.find(
        fk => fk.columnNames.indexOf('user_id') !== -1
      );
      if (userCreditsForeignKey) {
        await queryRunner.dropForeignKey('user_credits', userCreditsForeignKey);
      }
    }

    if (creditTransactionsTable) {
      const creditTransactionsForeignKey = creditTransactionsTable.foreignKeys.find(
        fk => fk.columnNames.indexOf('user_id') !== -1
      );
      if (creditTransactionsForeignKey) {
        await queryRunner.dropForeignKey('credit_transactions', creditTransactionsForeignKey);
      }
    }

    // 删除表
    await queryRunner.dropTable('credit_transactions', true);
    await queryRunner.dropTable('user_credits', true);
  }
} 